<?php

namespace app\admin\controller\addresslv;

use app\common\controller\Backend;
use fast\Tree;

/**
 *
 *
 * @icon fa fa-file
 */
class Addresslv extends Backend
{

    /**
     * Addresslv模型对象
     */
    protected $model = null;
    protected $noNeedRight = ["lists"];
    protected $noNeedLogin = [];


    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Addresslv');
        $tree = Tree::instance();
        $tree->init(collection($this->model->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $pid = 185;
        $arr = $tree->getTreeList($tree->getTreeArray($pid), 'name');
        $filteredData = array();
        for ($i = 0; $i < count($arr); $i++) {
            $v = $arr[$i];
            $filteredData[] = [
                'id' => $v['id'],
                'parent' => $v['pid'] ? $v['pid'] : '#',
                'text' => $v['name'],
                'type' => $v['type'],
                'status' => $v['status'],
            ];
        }
        $this->grouplist = $filteredData;
        $groupdata = [];
        foreach ($filteredData as $k => $v) {
            $groupdata[] = array(
                "id" => $v["id"],
                "name" => $v["text"],
            );
        }
        $this->groupdata = $groupdata;
        $this->view->assign("groupdata", $groupdata);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {

        if ($this->request->isAjax()) {
            $params = $this->request->post("row/a");
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 获取城市和学校过滤参数
            $city_id = $this->request->get("city_id");
            $school_id = $this->request->get("school_id");
            
            // 调试日志
            error_log("Addresslv Index - city_id: $city_id, school_id: $school_id");

            $total = $this->model
                ->where($where);
                
            // 添加城市过滤
            if (!empty($city_id)) {
                $total = $total->where("city_id", "=", $city_id);
            } else if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 2) {
                $total = $total->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            }
            
            // 添加学校过滤（教学点标签可能关联学校）
            if (!empty($school_id)) {
                // 查找与该学校相关的教学点标签
                $total = $total->where("school_id", "=", $school_id);
            }
            
            $total = $total->where("status", "<>", -1);
            $total = $total
                ->count();

            $list = $this->model
                ->where($where);
                
            // 添加城市过滤
            if (!empty($city_id)) {
                $list = $list->where("city_id", "=", $city_id);
            } else if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 2) {
                $list = $list->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            }
            
            // 添加学校过滤（教学点标签可能关联学校）
            if (!empty($school_id)) {
                // 查找与该学校相关的教学点标签
                $list = $list->where("school_id", "=", $school_id);
            }
            
            $list = $list->where("status", "<>", -1);
            $list = $list->order($sort, $order)
                ->order('weigh desc,id desc')
                ->limit($offset, $limit)
                ->select();

            //$this->model->getLastSql();
            $list = collection($list)->toArray();
            $tree = Tree::instance();
            $tree->init($list, 'pid');
            $arr = $tree->getTreeList($tree->getTreeArray(1), 'name');
            $filteredData = array();
            for ($i = 0; $i < count($arr); $i++) {
                $v = $arr[$i];
                $filteredData[] = [
                    'id' => $v['id'],
                    'parent' => $v['pid'] ? $v['pid'] : '#',
                    'pid' => $v['pid'] ? $v['pid'] : '#',
                    'text' => $v['name'],
                    'name' => $v['name'],
                    'type' => $v['type'],
                    'status' => $v['status'],
                    'starttime' => $v['starttime'],
                    'endtime' => $v['endtime'],
                    'entvirt' => $v['entvirt'],
                    'rel_id' => $v['rel_id'],
                    'rel_type' => model("Addresslv")->getRel_typeTextAttr($v['rel_type']),
                    'title' => $v['title'],
                ];
            }
            $list = $filteredData;
            $total = count($filteredData);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->assignconfig("relType", $_REQUEST['relType']);
        $_REQUEST['relId'] = $_REQUEST['relId'] ?? 0;
        $this->assignconfig("relId", $_REQUEST['relId']);
        return $this->view->fetch();
    }


    public function add()
    {

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            $r = $this->model->where("rel_type", "=", $params['rel_type'])
                ->where("rel_id", "=", $params['rel_type'])
                ->select();
            if ($params) {
                $data = array(
                    "type" => "file",
                    "pid" => $params['pid'],
                    "name" => $params['name'],
                    "title" => $params['name'],
                    "ismenu" => 0,
                    "createtime" => time(),
                    "updatetime" => time(),
                    "starttime" => $params['starttime'],
                    "endtime" => $params['endtime'],
                    "entvirt" => $params['entvirt'],
                    "status" => 1,
                    "rel_id" => $params['rel_id'],
                    "rel_type" => $params['rel_type'],
                    "province_id" => $params['province_id'],
                    "city_id" => $params['city_id'] ?? 0,
                    "district_id" => $params['district_id'] ?? 0,
                );

                $this->model->create($data);
                $this->success();
            }
            $this->error();
        }
        $this->assign('admin', $_SESSION['think']['admin']);
        $this->assignconfig('admin', $_SESSION['think']['admin']);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            $row->save($params);
            $this->success();
            return;
        }
        $this->view->assign("row", $row);
        $this->assign('admin', $_SESSION['think']['admin']);
        $this->assignconfig('admin', $_SESSION['think']['admin']);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $ids = explode(',', $ids);
            $count = $this->model->where('id', 'in', $ids)->delete();
            if ($count) {
                $this->success();
            }
        }
        $this->error();
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 组别禁止批量操作
        $this->error();
    }

    /**
     * 读取角色权限树
     *
     * @internal
     */
    public function roletree()
    {
        $this->view->assign("groupdata", $this->groupdata);
    }

    public function lists($ids = NULL)
    {
        $where = "where 1=1";
        if ($_SESSION['think']['admin']['group_id'] != 1) {
            $where .= " and city_id='{$_SESSION['think']['admin']['city_id']}'";
        }

        $r = $this->model->where("rel_type", "=", $_REQUEST['relType']);
        if($_REQUEST['relId']>0){
            $r=$r->where("rel_id", "=", $_REQUEST['relId']);
        }
        $r=$r->where("status", "=", 1)
            ->select();
        if (($_REQUEST['relType'] == "1" || $_REQUEST['relType'] == "school") && $_REQUEST['relId'] > 0) {
            $tablename = "School";
            $tableN = "eb_school";
        } else {
            $tablename = "Community";
            $tableN = "fa_community";
        }
        $r_name = model($tablename)->field("id,name")->where("id", "=", $_REQUEST['relId'])->select();
        if (empty($r) && !empty($r_name)) {
            $data = array(
                "type" => "file",
                "pid" => 0,
                "name" => $r_name[0]['name'],
                "title" => $r_name[0]['name'],
                "ismenu" => 0,
                "createtime" => time(),
                "updatetime" => time(),
                "status" => 1,
                "rel_id" => $_REQUEST['relId'],
                "rel_type" => $_REQUEST['relType'],
            );
            $this->model->create($data);
            $r=$this->model;
            if($_REQUEST['relType']>0){
                $r = $this->model->where("rel_type", "=", $_REQUEST['relType']);
            }
            $r =$r->where("rel_id", "=", $_REQUEST['relId'])
                ->select();
        }
        $data = $this->model;
        if($_REQUEST['relType']>0){
            $data = $data->where("rel_type", "=", $_REQUEST['relType']);
            if( $_REQUEST['relType']==1&&$_REQUEST['school_id']>0){
                $data = $data->where("rel_id", "=", $_REQUEST['school_id']);
            }elseif( $_REQUEST['relType']==2&&$_REQUEST['community_id']>0){
                $data = $data->where("rel_id", "=", $_REQUEST['community_id']);
            }elseif($_REQUEST['relId']>0) {
                $data = $data->where("rel_id", "=", $_REQUEST['relId']);
            }
        }

        $data = $data->select();
        $tree = Tree::instance();
        $tree->init($data, 'pid');
        $pid = 0;
        $arr = $tree->getTreeList($tree->getTreeArray($pid), 'name');
        $data = array();
        for ($i = 0; $i < count($arr); $i++) {
            $v = $arr[$i];
            $r = model("Subjectlv")->field("id,name")->where("addresslv_id", "=", $v['id'])->where("level", "=", 1)->select();
            if($r){
                $subject_id = $r[0]['id'];
            }else{
                $subject_id = 0;
            }
            $data[] = [
                'id' => $v['id'],
                'parent' => trim($v['pid'])?trim($v['pid']) : '#',
                'name' => $v['name'],
                'type' => $v['type'],
                'status' => $v['status'],
                'haschild' => $v['haschild'],
                'province_id' => $v['province_id'],
                'city_id' => $v['city_id'],
                'district_id' => $v['district_id'],
                'level' => $v['level'],
                'subject_id' => $subject_id,
            ];
        }
        $total = count($data);
        //$total = db()->query("select count(1) as c from  dev002_gxyusheng.{$tableN} $where")[0];
        echo json_encode(array("list" => $data, "total" => $total));
        exit;
    }
}